<?php
/**
 * http类
 * @Allan
 * Date: 2021/5/10 11:30
 */

namespace app\common\utils;


use think\facade\Env;
use think\facade\Log;

class Https
{
    /**请求超时时间**/
    public static $timeout = 300;

    public static function post($url, $param, $type = false, $log = true)
    {
        /**请求链接**/
        $url = trim($url);
        $sParam = is_array($param) ? json_encode($param) : $param;
        /**获取请求头信息**/
        $header = self::getHeader($type);

        $ch = curl_init();
        /**设置curl选项**/
        curl_setopt($ch, CURLOPT_URL, $url);
        if (strpos(strtolower($url), 'https') == 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        }
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $sParam);
        curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            /**请求失败**/
            $errorMsg = curl_error($ch);

            /**记录请求和响应信息**/
            if ($log) {
                self::apiError($url, $param, $errorMsg, $header);
            }
            curl_close($ch);
            return ['code' => 404, 'msg' => $errorMsg];
        }

        curl_close($ch);
        return $response;

    }

    /**
     * 获取请求头信息数组
     * @author
     * @param  boolean $needToken 是否需要令牌
     * @return array  返回请求头信息数组
     */
    protected static function getHeader($needToken = false)
    {
        $header = [];
//        $header[] = 'content-type:application/x-www-form-urlencoded;charset=UTF-8';
        $header[] = 'Content-Type: application/json; charset=utf-8';
        $header[] = 'appName:backstageManageSystem';
        $header[] = 'systemType:PC';
        if ($needToken) {
            $token = session('token');
            $header[] = 'token:' . $token;
        }

        return $header;
    }


    protected static function apiSuccess($url, $param, $response, $header = [])
    {
        $msg = '';
        $msg .= ($_SERVER['REMOTE_ADDR']??'REMOTE_ADDR 为空') . ' ' . ($_SERVER['REQUEST_URI']??'REQUEST_URI 为空') . PHP_EOL;
        $msg .= '请求时间：' . date('Y-m-d H:i:s') . PHP_EOL;
        $msg .= '请求地址：' . $url . PHP_EOL;
        $msg .= '请求参数：' . var_export($param, true) . PHP_EOL;
        $msg .= '响应参数：' . var_export($response, true) . PHP_EOL;
        if ($header) {
            $msg .= '请求头信息：' . var_export($header, true) . PHP_EOL;
        }
        self::writeLog($msg);
    }

    protected static function apiError($url, $param, $error, $header = [])
    {
        $msg = '';
        $msg .= ($_SERVER['REMOTE_ADDR']??'REMOTE_ADDR 为空') . ' ' . ($_SERVER['REQUEST_URI']??'REQUEST_URI 为空') . PHP_EOL;
        $msg .= '请求时间：' . date('Y-m-d H:i:s') . PHP_EOL;
        $msg .= '请求地址：' . $url . PHP_EOL;
        $msg .= '请求参数：' . var_export($param, true) . PHP_EOL;
        $msg .= '错误信息：' . $error . PHP_EOL;
        if ($header) {
            $msg .= '请求头信息：' . var_export($header, true) . PHP_EOL;
        }
        self::writeLog($msg);
    }


    protected static function writeLog($msg)
    {
        $file = root_path() . sprintf('/runtime/https/%s/%s.log', date('Ym'), date('d'));
        //自动创建日志目录
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        @file_put_contents($file, $msg, FILE_APPEND);
    }
}